<template>
  <div class="task-assign">
    <h1 class="page-title">任务分配</h1>

    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" class="plan-tabs">
      <!-- 创建新计划标签 -->
      <el-tab-pane label="创建新计划" name="create">
        <div class="create-plan-content">
          <!-- 计划设置 -->
          <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>计划设置</span>
        </div>
      </template>

      <el-form :model="planForm" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称">
              <el-input
                v-model="planForm.planName"
                placeholder="例如：张小宝的第一周训练计划"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划类型">
              <el-radio-group v-model="planForm.planType">
                <el-radio label="daily">每日计划</el-radio>
                <el-radio label="weekly">每周计划</el-radio>
                <el-radio label="custom">自定义</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="planForm.startDate"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="planForm.endDate"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 任务分配区域 -->
    <el-row :gutter="20">
      <!-- 待分配任务库 -->
      <el-col :span="12">
        <el-card class="content-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待分配任务库 (共 {{ totalTasks }} 个)</span>
              <el-button type="text" size="small" @click="loadAvailableTasks">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <div class="task-filters">
            <el-select
              v-model="taskFilter.domain"
              placeholder="筛选领域"
              clearable
              size="small"
              style="width: 120px"
              @change="handleFilterChange"
            >
              <el-option
                v-for="item in domainOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="taskFilter.difficulty"
              placeholder="筛选难度"
              clearable
              size="small"
              style="width: 120px"
              @change="handleFilterChange"
            >
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <div v-loading="loadingTasks" class="task-pool">
            <el-empty v-if="availableTasks.length === 0" description="暂无任务" />
            
            <div
              v-for="task in availableTasks"
              :key="task.id"
              class="task-item"
              draggable="true"
              @dragstart="handleDragStart($event, task)"
            >
              <div class="task-info">
                <h4>{{ task.title }}</h4>
                <div class="task-tags">
                  <el-tag size="small" type="info">
                    {{ getDomainText(task.domain) }}
                  </el-tag>
                  <el-tag size="small" type="warning">
                    {{ getDifficultyText(task.difficulty) }}
                  </el-tag>
                </div>
              </div>
              <el-button
                type="primary"
                size="small"
                @click="addTaskToPlan(task)"
              >
                添加
              </el-button>
            </div>
          </div>

          <!-- 分页组件 -->
          <div v-if="totalTasks > 0" class="pagination-container">
            <el-pagination
              v-model:current-page="taskPagination.pageNum"
              v-model:page-size="taskPagination.pageSize"
              :page-sizes="[10, 20, 50]"
              :total="totalTasks"
              layout="total, sizes, prev, pager, next"
              small
              @size-change="handleTaskSizeChange"
              @current-change="handleTaskPageChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 已分配任务区 -->
      <el-col :span="12">
        <el-card class="content-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>已分配任务 ({{ assignedTasks.length }})</span>
              <el-button
                type="primary"
                size="small"
                :loading="saving"
                @click="savePlan"
              >
                <el-icon><Check /></el-icon>
                保存计划
              </el-button>
            </div>
          </template>

          <div
            class="assigned-area"
            @drop="handleDrop"
            @dragover.prevent
          >
            <el-empty
              v-if="assignedTasks.length === 0"
              description="拖拽或点击添加按钮来分配任务"
            />

            <div
              v-for="(item, index) in assignedTasks"
              :key="index"
              class="assigned-item"
            >
              <div class="assigned-info">
                <div class="assigned-task">
                  <h4>{{ item.task.title }}</h4>
                  <div class="task-tags">
                    <el-tag size="small" type="info">
                      {{ getDomainText(item.task.domain) }}
                    </el-tag>
                  </div>
                </div>

                <div class="assigned-config">
                  <el-form :inline="true" size="small">
                    <el-form-item label="日期">
                      <el-date-picker
                        v-model="item.scheduledDate"
                        type="date"
                        placeholder="选择日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        style="width: 150px"
                      />
                    </el-form-item>
                    <el-form-item label="时间">
                      <el-time-picker
                        v-model="item.scheduledTime"
                        placeholder="选择时间"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        style="width: 120px"
                      />
                    </el-form-item>
                  </el-form>
                </div>
              </div>

              <div class="assigned-actions">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeTask(index)"
                >
                  移除
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
        </div>
      </el-tab-pane>

      <!-- 我的计划标签 -->
      <el-tab-pane name="myPlans">
        <template #label>
          <span class="tab-label">
            <el-icon><Document /></el-icon>
            我的计划
            <el-badge v-if="myPlans.length > 0" :value="myPlans.length" class="plan-badge" />
          </span>
        </template>

        <!-- 我的计划列表 -->
        <div v-loading="loadingPlans" class="my-plans-content">
          <el-empty v-if="myPlans.length === 0" description="还没有创建计划，去创建第一个计划吧！">
            <el-button type="primary" @click="activeTab = 'create'">创建计划</el-button>
          </el-empty>

          <div v-else class="plans-grid">
            <el-card
              v-for="plan in myPlans"
              :key="plan.id"
              class="plan-card"
              shadow="hover"
            >
              <div class="plan-header">
                <div class="plan-title-section">
                  <h3>{{ plan.planName }}</h3>
                  <el-tag :type="getPlanStatus(plan).type" size="small">
                    {{ getPlanStatus(plan).text }}
                  </el-tag>
                </div>
                <div class="plan-actions">
                  <el-button
                    type="primary"
                    text
                    size="small"
                    @click="viewPlanDetail(plan)"
                  >
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-button>
                  <el-button
                    type="danger"
                    text
                    size="small"
                    @click="handleDeletePlan(plan.id, plan.planName)"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>

              <div class="plan-meta">
                <div class="meta-item">
                  <el-icon class="meta-icon"><Calendar /></el-icon>
                  <span class="meta-label">计划周期：</span>
                  <span class="meta-value">
                    {{ formatDate(plan.startDate) }} ~ {{ formatDate(plan.endDate) }}
                  </span>
                </div>
                <div class="meta-item">
                  <el-icon class="meta-icon"><List /></el-icon>
                  <span class="meta-label">计划类型：</span>
                  <span class="meta-value">{{ getPlanTypeText(plan.planType) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon class="meta-icon"><Clock /></el-icon>
                  <span class="meta-label">创建时间：</span>
                  <span class="meta-value">{{ formatDate(plan.createTime) }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getTaskListPage } from '@/api/task'
import { savePlan as savePlanApi, getMyPlans, deletePlan as deletePlanApi } from '@/api/plan'
import {
  DOMAIN_MAP,
  DIFFICULTY_MAP,
  DOMAIN_OPTIONS,
  DIFFICULTY_OPTIONS
} from '@/utils/constants'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

const activeTab = ref('create')
const loadingTasks = ref(false)
const loadingPlans = ref(false)
const saving = ref(false)
const availableTasks = ref([])
const totalTasks = ref(0)
const assignedTasks = ref([])
const myPlans = ref([])

const domainOptions = DOMAIN_OPTIONS
const difficultyOptions = DIFFICULTY_OPTIONS

// 任务分页参数
const taskPagination = reactive({
  pageNum: 1,
  pageSize: 20
})

// 计划表单
const planForm = reactive({
  planName: '',
  planType: 'weekly',
  startDate: dayjs().format('YYYY-MM-DD'),
  endDate: dayjs().add(7, 'day').format('YYYY-MM-DD')
})

// 任务筛选
const taskFilter = reactive({
  domain: '',
  difficulty: null
})

const getDomainText = (domain) => {
  return DOMAIN_MAP[domain] || domain
}

const getDifficultyText = (difficulty) => {
  return DIFFICULTY_MAP[difficulty] || difficulty
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

// 获取计划类型文本
const getPlanTypeText = (type) => {
  const typeMap = {
    daily: '每日计划',
    weekly: '每周计划',
    custom: '自定义'
  }
  return typeMap[type] || type
}

// 获取计划状态
const getPlanStatus = (plan) => {
  const now = dayjs()
  const startDate = dayjs(plan.startDate)
  const endDate = dayjs(plan.endDate)
  
  if (now.isBefore(startDate)) return { text: '未开始', type: 'info' }
  if (now.isAfter(endDate)) return { text: '已结束', type: 'info' }
  return { text: '进行中', type: 'success' }
}

// 加载可用任务 - 使用分页API
const loadAvailableTasks = async () => {
  loadingTasks.value = true
  try {
    const params = {
      pageNum: taskPagination.pageNum,
      pageSize: taskPagination.pageSize
    }
    if (taskFilter.domain) params.domain = taskFilter.domain
    if (taskFilter.difficulty) params.difficulty = taskFilter.difficulty

    const pageResult = await getTaskListPage(params)
    availableTasks.value = pageResult.records || []
    totalTasks.value = pageResult.total || 0
  } catch (error) {
    console.error('加载任务失败:', error)
    availableTasks.value = []
    totalTasks.value = 0
  } finally {
    loadingTasks.value = false
  }
}

// 筛选条件变化
const handleFilterChange = () => {
  taskPagination.pageNum = 1
  loadAvailableTasks()
}

// 分页大小变化
const handleTaskSizeChange = (newSize) => {
  taskPagination.pageSize = newSize
  taskPagination.pageNum = 1
  loadAvailableTasks()
}

// 页码变化
const handleTaskPageChange = (newPage) => {
  taskPagination.pageNum = newPage
  loadAvailableTasks()
}

// 添加任务到计划
const addTaskToPlan = (task) => {
  assignedTasks.value.push({
    task,
    taskId: task.id,
    scheduledDate: planForm.startDate,
    scheduledTime: '09:00:00',
    orderIndex: assignedTasks.value.length + 1
  })
  ElMessage.success('已添加到计划')
}

// 拖拽开始
const handleDragStart = (event, task) => {
  event.dataTransfer.effectAllowed = 'copy'
  event.dataTransfer.setData('task', JSON.stringify(task))
}

// 放置
const handleDrop = (event) => {
  event.preventDefault()
  const taskData = event.dataTransfer.getData('task')
  if (taskData) {
    const task = JSON.parse(taskData)
    addTaskToPlan(task)
  }
}

// 移除任务
const removeTask = (index) => {
  assignedTasks.value.splice(index, 1)
  ElMessage.info('已移除')
}

// 加载我的计划列表
const loadMyPlans = async () => {
  loadingPlans.value = true
  try {
    const userId = userStore.userInfo?.userId
    if (!userId) return

    const data = await getMyPlans({ userId })
    myPlans.value = data || []
  } catch (error) {
    console.error('加载计划列表失败:', error)
    myPlans.value = []
  } finally {
    loadingPlans.value = false
  }
}

// 删除计划
const handleDeletePlan = async (planId, planName) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除计划"${planName}"吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deletePlanApi(planId)
    ElMessage.success('计划已删除')
    loadMyPlans()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除计划失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 查看计划详情
const viewPlanDetail = (plan) => {
  if (!plan.id) {
    ElMessage.error('计划ID不存在')
    return
  }
  router.push({
    name: 'PlanDetail',
    params: { id: plan.id }
  })
}

// 保存计划
const savePlan = async () => {
  if (!planForm.planName) {
    ElMessage.warning('请输入计划名称')
    return
  }

  if (assignedTasks.value.length === 0) {
    ElMessage.warning('请至少添加一个任务')
    return
  }

  // 验证每个任务是否设置了日期和时间
  const hasEmptySchedule = assignedTasks.value.some(
    item => !item.scheduledDate || !item.scheduledTime
  )
  if (hasEmptySchedule) {
    ElMessage.warning('请为所有任务设置日期和时间')
    return
  }

  saving.value = true
  try {
    const userId = userStore.userInfo?.userId
    const planData = {
      userId,
      ...planForm,
      planItems: assignedTasks.value.map(item => ({
        taskId: item.taskId,
        scheduledDate: item.scheduledDate,
        scheduledTime: item.scheduledTime,
        assignedTo: userId,
        orderIndex: item.orderIndex
      }))
    }

    await savePlanApi(planData)
    ElMessage.success('计划保存成功！')
    
    // 重置表单
    assignedTasks.value = []
    planForm.planName = ''
    planForm.startDate = dayjs().format('YYYY-MM-DD')
    planForm.endDate = dayjs().add(7, 'day').format('YYYY-MM-DD')
    
    // 刷新计划列表并切换到"我的计划"标签
    loadMyPlans()
    activeTab.value = 'myPlans'
  } catch (error) {
    console.error('保存计划失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadAvailableTasks()
  loadMyPlans()
})
</script>

<style scoped>
.plan-tabs {
  margin-bottom: 20px;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
}

.plan-badge {
  margin-left: 6px;
}

.create-plan-content,
.my-plans-content {
  min-height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.task-filters {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.task-pool {
  max-height: 500px;
  overflow-y: auto;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background: #f9f9f9;
  border-radius: 8px;
  border-left: 3px solid #ffb3d9;
  cursor: move;
  transition: all 0.3s;
}

.task-item:hover {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transform: translateX(5px);
}

.task-info {
  flex: 1;
}

.task-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.task-tags {
  display: flex;
  gap: 8px;
}

.assigned-area {
  min-height: 600px;
  max-height: 600px;
  overflow-y: auto;
  padding: 10px;
  background: #fafafa;
  border-radius: 8px;
  border: 2px dashed #dcdfe6;
}

.assigned-area:empty {
  display: flex;
  align-items: center;
  justify-content: center;
}

.assigned-item {
  padding: 15px;
  margin-bottom: 15px;
  background: #fff;
  border-radius: 8px;
  border-left: 4px solid #ffc299;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.assigned-info {
  margin-bottom: 10px;
}

.assigned-task h4 {
  margin: 0 0 8px 0;
  font-size: 15px;
  color: #303133;
}

.assigned-config {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.assigned-config .el-form {
  margin: 0;
}

.assigned-config .el-form-item {
  margin-bottom: 0;
}

.assigned-actions {
  display: flex;
  justify-content: flex-end;
}

/* 我的计划样式 */
.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.plan-card {
  border-radius: 12px;
  transition: all 0.3s;
  border-left: 4px solid #ffb3d9;
}

.plan-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(255, 179, 217, 0.2);
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f5f7fa;
}

.plan-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.plan-title-section h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.plan-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.plan-meta {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  gap: 6px;
}

.meta-icon {
  color: #ffb3d9;
  font-size: 16px;
}

.meta-label {
  color: #909399;
  min-width: 80px;
}

.meta-value {
  color: #606266;
  font-weight: 500;
  flex: 1;
}

@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 20px;
  }

  .assigned-config .el-form-item {
    display: block;
    margin-bottom: 10px;
  }

  .assigned-config .el-date-picker,
  .assigned-config .el-time-picker {
    width: 100% !important;
  }

  .plans-grid {
    grid-template-columns: 1fr;
  }

  .plan-header {
    flex-direction: column;
    gap: 12px;
  }

  .plan-actions {
    width: 100%;
  }
}
</style>
